package com.hong.cloud.mall.practice.cartorder.config;

import com.hong.cloud.mall.practice.cartorder.service.OrderService;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 描述：定时任务配置
 */

@Component
public class JobConfiguration {
    private final Logger log = LoggerFactory.getLogger(JobConfiguration.class);
    @Autowired
    private OrderService orderService;

    @Resource
    RedissonClient redissonClient;

    @Scheduled(cron = "0 0/5 * * * ?") //
    public void cancelUnpaidOrder() throws InterruptedException {
        RLock redissonLock = redissonClient.getLock("redissonLock");
        boolean b = redissonLock.tryLock();
        if (b) {
            try{
                System.out.println("redisson锁+1");
                orderService.getUnpaidOrderList().forEach(order -> {
                    log.info("取消订单，订单编号：{}", order.getOrderNo());
                    orderService.cancel(order.getOrderNo(), true);
                });
            }finally {
                redissonLock.unlock();
                System.out.println("redisson锁已释放");
            }
        } else {
            System.out.println("redisson锁未获取到");
        }
    }
}
